/*
 * 单用户使用时的各个函数
 */

#include <stdio.h>
#include "gui.h"
#include "fivekernel.h"
#include "ai.h"

static int single_done = 0;
static int click_able = 0;	//对棋盘进行禁用

//当棋盘按下时发生
void ACALLBACK single_board_click(int px, int py)
{
	int win;
	if (!click_able) return;
	
	if (krnl_checker_put(krnl_get_turn(), px, py, &win)) return;
	if (win > 0) {
		struct Msgbox *msg = msgbox_new("Well done!", "You win this game.", 0, MSG_OK);
		msgbox_run(msg);
		msgbox_delete(msg);
		click_able = 0;
		return;
	} else if (win < 0) {
		struct Msgbox *msg = msgbox_new("Oops!", "You violate the rules.", 0, MSG_OK);
		msgbox_run(msg);
		msgbox_delete(msg);
		click_able = 0;
		return;
	}

	int rx, ry;
	computer(krnl_get_turn(), 2, global_board,
		 15, &rx, &ry);
	krnl_checker_put(krnl_get_turn(), rx, ry, &win);
	if (win > 0) {
		struct Msgbox *msg = msgbox_new("Oops!", "AI win this game.", 0, MSG_OK);
		msgbox_run(msg);
		msgbox_delete(msg);
		click_able = 0;
		return;
	} else if (win < 0) {
		struct Msgbox *msg = msgbox_new("Err..h", "AI violates the rules.", 0, MSG_OK);
		msgbox_run(msg);
		msgbox_delete(msg);
		click_able = 0;
		return;
	}
}

//当新建游戏按钮按下时发生
void ACALLBACK single_new()
{
	struct Msgbox *msg = msgbox_new("Question?", "Hold black?", 0, MSG_YES | MSG_NO | MSG_CANCEL);
	int ret = msgbox_run(msg);
	msgbox_delete(msg);
	switch (ret) {
		case MSG_YES:
			krnl_reset();
			click_able = 1;
			break;
		case MSG_NO:
		{
			int rx, ry, win;
			krnl_reset();
			computer(krnl_get_turn(), 2, global_board,
				 15, &rx, &ry);
			krnl_checker_put(krnl_get_turn(), rx, ry, &win);
			click_able = 1;
			break;
		}
	}
}

//悔棋按钮按下时发生
void ACALLBACK single_retract()
{
	printf("retract clicked\n");
}

//保存
void ACALLBACK single_save()
{
	steps(0, 0, SAVE_FILE, "cbar.five");
	printf("save clicked\n");
}

//读取
void ACALLBACK single_load()
{
	krnl_reset();
	click_able = 1;
	steps(0, 0, LOAD_FILE, "cbar.five");
	printf("load clicked\n");
}

void ACALLBACK single_ret()
{
	single_done = 1;
}

void single_game_start()
{
	single_done = 0;
	single_new();
	
	while (!single_done) {
		gui_event_idle(NULL);
		gui_render();
		SDL_Delay(10);
	}
}
